<?php

App::import('lib', 'Optimiser.optimiser');

class AppController extends Controller {

    var $admin = false;
    var $authorized = false;
    var $authorizedUser = null;
    var $authorizedAsAdmin = false;
    var $layout = "lewandowski.cms";
    var $components = array(
        'Auth' => array(
            'authorize' => 'controller',
            'actionPath' => 'controllers/',
            'userModel' => 'user',
            'loginAction' => array(
                'controller' => 'users',
                'action' => 'login',
                'plugin' => false,
                'admin' => false
            ),
            'loginRedirect' => array('controller' => 'frontpage', 'action' => 'index'),
            'logoutRedirect' => array('controller' => 'frontpage', 'action' => 'index'),
            'loginError' => 'Podałeś zły login lub hasło.',
            'authError' => 'Niestety, nie masz dostępu do tej części serwisu.'
        ),
        'Session'
    );

    public function __construct() {
        parent::__construct();
        $this->set("frontpage", false);

        $this->set("authorized", false);
    }

    public function isAuthorized() {
        if ($this->admin) {
            return ($this->authorized && $this->authorizedAsAdmin);
        }
        else
            return true;
    }

    public function beforeFilter() {
        parent::beforeFilter();

        if(!$this->admin) $this->admin = (isset($this->params['admin'])? ($this->params['admin']? true : false) : false);


        $this->authorized = !($this->Auth->user() == null);

        $this->set("authorized", $this->authorized);

        if ($this->authorized) {
            $this->authorizedUser = $this->Auth->user();
            if (isset($this->authorizedUser['user']))
                $this->authorizedUser = $this->authorizedUser['user'];
            else
                $this->authorizedUser = $this->authorizedUser['User'];

            $this->set("authorizedUser", $this->authorizedUser);

            if ($this->authorizedUser['role'] == "admin") {
                $this->authorizedAsAdmin = true;
            }

            $this->set("authorizedAsAdmin", $this->authorizedAsAdmin);
            //var_dump($this->authorizedUser);
        }

        if ($this->admin) {
            $this->layout = "admin";
            $this->helpers[] = "Admin";
            $this->helpers[] = "Blueprint";
        }
        else
            $this->Auth->allow($this->params['action']);
    }

    public function beforeRender() {
        parent::beforeRender();
        if (isset($this->title)) {
            $this->set('title_for_layout', $this->title);
        }
        if (empty($this->layout) || $this->layout == "default") {
            $this->set("menu_entries", Configure::read("Autoconfig.menu_entries"));
        }
    }

    public function trigger404() {
        $this->cakeError('error404');
    }

}

?>
